import { Form, Input, Modal } from "antd";
import { useEffect, useState } from "react";

const CollectionCreateForm = ({ onFormInstanceReady, info }) => {
  const [form] = Form.useForm();
  console.log(form);
  useEffect(() => {
    console.log("info", info);
    if (info && info.id) {
      console.log("info", info);
      form.setFieldsValue({
        title: info.title,
        content: info.content,
      });
    }
    onFormInstanceReady(form);
  },);
  return (
    <Form form={form}>
      <Form.Item
        label="标题"
        name="title"
        rules={[{ required: true, message: "请输入标题" }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="内容"
        name="content"
        rules={[{ required: true, message: "内容" }]}
      >
        <Input.TextArea></Input.TextArea>
      </Form.Item>
    </Form>
  );
};

export default function FormAdd({ isOpen, title, handleCancel, onCreate, info }) {
  const [formInstance, setFormInstance] = useState();
  console.log(formInstance);
  return (
    <>
      {isOpen && (
        <Modal
          open={isOpen}
          title={title}
          onOk={async () => {
            try {
              console.log(formInstance);
              const values = await formInstance?.validateFields();
              console.log(values);
              formInstance?.resetFields();
              onCreate(values);
            } catch (error) {
              console.log("Failed:", error);
            }
          }}
          onCancel={() => {
            formInstance?.resetFields();
            handleCancel();
          }}
        >
          <CollectionCreateForm
            info={info}
            onFormInstanceReady={(instance) => setFormInstance(instance)}
          />
        </Modal>
      )}
    </>
  );
}
